<template>
    <div class="waitConfirmed">
        <search :columns="searchData" @getSearch="getSearch(arguments)" key="search"></search>
        <div class="list-layout mt16">
            <div class="btns clear">
                <span class="title">{{ $t('common.listInformation') }}</span>
                <template v-if="status==0">
                    <Button @click="exportTemplate">
                    {{ $t('common.Download') }}</Button>
                <Button @click="importExcelShow">
                    {{ $t('common.Import') }}
                </Button>
                <Button @click="handleBatchDisabled"
                    v-if="delIds.length">
                    {{ $t('maintenance.Disable') }}
                </Button>
                <Button @click="handleBatchDelete" v-if="delIds.length">{{
                    $t('common.Delete') }}
                </Button>
                <Button slot="btns" @click="$emit('addMaintain',true)">新建点检计划</Button>
                </template>
                
                <Button @click="getTableColumns(columns)">{{ handleContextMenuStatus ? $t('显示操作栏') : $t('隐藏操作栏') }}</Button>
            </div>
            <div class="tableContent">
                <Table border class="resizable-table" @on-column-width-resize="onColumnWidthResize" ref="selection"
                    :columns="columnsList" :data="data" @on-selection-change="onSelectChange">
                    <template slot-scope="{ row }" slot="action">
                        <span class="operationBtn" @click="confirm(row)"><i class="iconfont zy-common-jinyong"></i>
                            {{ status==0 ? '禁用':'启用'}}
                        </span>
                        <span class="operationBtn" @click="look(row)"><i
                                class="iconfont zy-common-chakan"></i>{{ $t('common.Check') }}</span>
                        <span class="operationBtn" @click="edit(row, 'copy')"><i
                                class="iconfont zy-common-bianji"></i>{{ $t('复制') }}</span>
                        <span class="operationBtn" @click="edit(row)"><i
                                class="iconfont zy-common-bianji"></i>{{ $t('common.Edit') }}</span>
                        <span class="operationBtn" @click="deleteRow(row)"><i
                                class="iconfont zy-common-shanchu"></i>{{ $t('common.Delete') }}</span>
                    </template>
                </Table>
            </div>
            <div class="pageWrap mt16">
                <pageLeftTitle :total="total" :selected="delIds.length" />
                <Page :total="total" :page-size="pageSize" :page-size-opts="$variable.pageSizes" :current="pageNum"
                    @on-change="changePageNum" @on-page-size-change="changePageSize" show-sizer show-total />
            </div>
        </div>
        <Modal :mask-closable="false" v-model="delFaultCodeShowF" :title="$t('common.Delete')" class="modal-title-layout">
            <div class="icon red">
                <i class="iconfont zy-common-shanchu"></i>
            </div>
            <p class="title">
                <span>{{ $t('maintenance.delTip') }}</span>
            </p>
            <div slot="footer">
                <Button type="default" @click="delFaultCodeShowF = false">{{ $t('common.Cancle') }}</Button>
                <Button type="primary" :loading="delLoading" @click="deleteOk">{{ $t('maintenance.Confirmed') }}
                </Button>
            </div>
        </Modal>

        <Modal :mask-closable="false" v-model="confirmFaultCodeShowF" class="modal-content-layout"
            :title="$t('maintenance.disabledPlan')">
            <Form ref="disabledPlanValidate" :rules="ruleValidate" :model="formInline">
                <FormItem :label="$t('maintenance.disabledCycle')" class="item" prop="disableCycle">
                    <Row>
                        <Col span="24">
                        {{ $t('maintenance.monthMultiplied') }}
                        </Col>
                        <Col span="24">
                        <InputNumber :min="0" :formatter="value => `${parseInt(value)}`" style="width: 100%"
                            v-model="formInline.disableCycle" clearable></InputNumber>
                        </Col>
                        <Col span="24" style="color: #ff0000">{{ $t('maintenance.disableTask') }}</Col>
                    </Row>
                </FormItem>
                <FormItem :label="$t('maintenance.disabledQues')" class="item" prop="reason">
                    <Input type="textarea" v-model="formInline.reason" clearable :rows="6"></Input>
                </FormItem>
                <FormItem label="" class="item">
                    <Row>
                        <Col style="color: #ff0000">
                        {{ $t('maintenance.disabledTip') }}
                        </Col>
                    </Row>
                </FormItem>
            </Form>

            <div slot="footer">
                <Button type="default" @click="disabledCancel">{{ $t('common.Cancle') }}</Button>
                <Button type="primary" :loading="disabledLoading" @click="disabledOk">
                    {{ $t('maintenance.Confirmed') }}
                </Button>
            </div>
        </Modal>
        <Modal :mask-closable="false" v-model="create" :title="`${$t('common.Edit')}`">
            <Form class="formList" :model="formItem" label-position="top" inline>
                <FormItem :label="`${$t('ledger.EquipmentType')}:`" class="item" required>
                    <Select v-model="formItem.classification" filterable clearable
                        :placeholder="`${$t('common.inputInfo')}`">
                        <Option v-for="(item, index) of classification" :value="item.key" :key="index">{{
                            item.name
                        }}
                        </Option>
                    </Select>
                </FormItem>
                <FormItem :label="`${$t('maintenance.MaintenanceItem')}:`" required>
                    <Input type="text" v-model="formItem.materialCode" :placeholder="`${$t('common.inputInfo')}`"
                        class="inputBorder" :maxlength="32"></Input>
                </FormItem>
                <FormItem :label="`${$t('maintenance.Frequency')}:`" class="item" required>
                    <Select v-model="formItem.period" filterable clearable :placeholder="`${$t('common.inputInfo')}`">
                        <Option v-for="(item, index) of period" :value="item.key" :key="index">{{ item.name }}</Option>
                    </Select>
                </FormItem>
                <FormItem :label="`${$t('spareParts.Specification')}:`">
                    <Input type="text" v-model="formItem.materialCode" :placeholder="`${$t('common.inputInfo')}`"
                        class="inputBorder" :maxlength="32"></Input>
                </FormItem>
                <FormItem :label="`${$t('maintenance.Checkmethods')}:`">
                    <Input type="text" v-model="formItem.materialCode" :placeholder="`${$t('common.inputInfo')}`"
                        class="inputBorder" :maxlength="32"></Input>
                </FormItem>
                <FormItem :label="`${$t('maintenance.Checktools')}:`">
                    <Input type="text" v-model="formItem.materialCode" :placeholder="`${$t('common.inputInfo')}`"
                        class="inputBorder" :maxlength="32"></Input>
                </FormItem>
                <FormItem :label="`${$t('maintenance.UpperLimit')}:`">
                    <Input type="text" v-model="formItem.materialCode" :placeholder="`${$t('common.inputInfo')}`"
                        class="inputBorder" :maxlength="32"></Input>
                </FormItem>
                <FormItem :label="`${$t('maintenance.LowerLimit')}:`">
                    <Input type="text" v-model="formItem.materialCode" :placeholder="`${$t('common.inputInfo')}`"
                        class="inputBorder" :maxlength="32"></Input>
                </FormItem>
                <FormItem :label="`${$t('maintenance.Unit')}:`">
                    <Input type="text" v-model="formItem.materialCode" :placeholder="`${$t('common.inputInfo')}`"
                        class="inputBorder" :maxlength="32"></Input>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button type="default" @click="create = false">{{ $t('common.Cancle') }}</Button>
                <Button type="primary" @click="addOk">{{ $t('maintenance.Confirmed') }}</Button>
            </div>
        </Modal>
        <Modal :mask-closable="false" v-model="actualShowF" :title="$t('maintenance.disabledLog')" width="1200">
            <Table :columns="receiveCol" :data="receivedataArr"></Table>
        </Modal>

        <importExcelModal :importExcelStateF="importExcelState" v-if="importExcelState"
            @importExcelChange="importExcelChange"></importExcelModal>
    </div>
</template>

<script>
import importExcelModal from "@/components/importExcel.vue";
import fileDownload from "js-file-download";
import search from "@/components/curd/searchList.vue";
import toggleTableOperation from "@/mixins/toggleTableOperation";
export default {
    name: 'waitConfirmed',
    mixins: [toggleTableOperation],
    components: { importExcelModal,search },
    props: ['device', 'effPlanList', 'effPlanTotal', 'status', 'planIds'],
    data() {
        return {
            customCacheKey: "planefficaciouswaitConfirmed",
            deviceTypeList: [],
            deviceNameList: [],
            text: '',
            planId: '',
            delId: '',
            delIds: this.planIds,
            disabledStatus: '',
            total: this.effPlanTotal,
            pageSize: 10,
            pageNum: 1,
            pageSizeOption: [10, 20, 30, 40],
            delLoading: false,
            delFaultCodeShowF: false,//是否显示删除弹窗
            confirmFaultCodeShowF: false,
            disabledLoading: false,
            create: false,
            actualShowF: false,
            searchParams: {},
            formItem: {},
            formInline: {
                disableCycle: null,
                reason: ''
            },
            ruleValidate: {
                disableCycle: [
                    { required: true, type: 'number', message: "请输入禁用周期", trigger: "blur" },
                ]
            },
            classification: [
                { name: 'CNC', key: 'CNC' },
                { name: 'PLC', key: 'PLC' },
                { name: 'IPC', key: 'IPC' },
            ],
            receiveCol: [
                { title: '禁用时间', key: 'createTime' },
                { title: '禁用人', key: 'createName' },
                { title: '禁用周期(月)', key: 'disableCycle' },
                { title: '禁用原因', key: 'reason' },
                { title: '启用时间', key: 'enableTime' },
                { title: '启用人', key: 'updateName' }
            ],
            period: [
                { name: '月度', key: 'month' },
                { name: '季度', key: 'quarter' },
                { name: '年度', key: 'year' },
            ],
            searchData: [
                // {
                //     title: "安装位置",
                //     key: "installPosition",
                //     type: "cascader",
                //     dicUrl: "/basic/organization/findListByToken?level=0",
                //     params: {
                //         label: "name",
                //         value: "code",
                //         children: "children"
                //     }
                // },
                {
                    title: "计划",
                    key: "planName"
                },
                {
                    title: "设备等级",
                    key: "deviceGrade",
                    type: "select",
                    dicData: [
                        { label: 'A', value: 'A' },
                        { label: 'B', value: 'B' },
                        { label: 'C', value: 'C' },
                    ]
                },
                {
                    title: "设备类别",
                    key: "deviceCategory"
                },
                {
                    title: "点检级别",
                    key: "planLevel",
                    type: "select",
                    dicData:[
                        { label: "一级点检", value: '一级点检' },
                        { label: "二级点检", value: '二级点检' },
                        { label: "三级点检", value: '三级点检' },
                    ]
                },
                {
                    title: "点检周期",
                    key: "cycleUnit",
                    type: "select",
                    dicData: [
                        // { name: "全部", key: "" },
                        { name: "日", key: "1" },
                        // { name: "周", key: "2" },
                        // { name: "月", key: "3" },
                        // { name: "季度", key: "4" },
                        // { name: "半年度", key: "5" },
                        // { name: "年度", key: "6" },
                        { name: "班次", key: "7" },
                        { name: "小时", key: "8" },
                    ],
                    params:{
                        label:'name',
                        value:'name'
                    }
                },
                {
                    title: "设备编号",
                    key: "deviceNo",
                },
            ],
            columns: [
                {
                    type: 'selection',
                    align: 'center',
                    width: 60
                },
                {
                    title: `${this.$t('计划')}`,
                    key: 'planName',
                    width: 200,
                    align: "left",
                    tooltip: true,
                    resizable: true,
                },
                {
                    title: `${this.$t('设备等级')}`,
                    key: 'deviceGrade',
                    minWidth: 160,
                    align: "center",
                    tooltip: true,
                    resizable: true,
                },
                {
                    title: `${this.$t('设备类别')}`,
                    key: "deviceCategory",
                    minWidth: 180,
                    align: "center",
                    tooltip: true,
                    resizable: true,
                },
                {
                    title: `${this.$t('点检级别')}`,
                    key: "planLevel",
                    minWidth: 160,
                    align: "center",
                    tooltip: true,
                    resizable: true,
                    // render: (h, params) => {
                    //     return h('div', [
                    //         h('span', {}, this.levelList.find(val => val.key === params.row.itemLevel).name)
                    //     ])
                    // }
                },
                {
                    title: `${this.$t('点检周期')}`,
                    key: "cycleUnit",
                    minWidth: 160,
                    align: "center",
                    tooltip: true,
                    resizable: true,
                },
                // {title: '点检方式', key: 'maintainName', minWidth: 100,align: "center", tooltip: true},
                {
                    title: `${this.$t('触发间隔')}`,
                    key: 'triggerCycleText',
                    minWidth: 150,
                    align: "center",
                    tooltip: true,
                    resizable: true,
                    render: (h, params) => {
                        return h('div', [
                            h('span', {},params.row.planCycle+""+params.row.cycleUnit)
                        ])
                    },
                },
                {
                    title: `${this.$t('首次生成时间')}`,
                    key: 'firstTime',
                    minWidth: 200,
                    align: "center",
                    tooltip: true,
                    resizable: true
                },
                {
                    title: `${this.$t('计划截止时间')}`,
                    key: 'endTime',
                    minWidth: 200,
                    align: "center",
                    tooltip: true,
                    resizable: true
                },
                {
                    title: `${this.$t('任务存活时间')}`,
                    key: 'liveTimeD',
                    minWidth: 190,
                    align: "center",
                    tooltip: true,
                    resizable: true,
                    render: (h, params) => {
                        return h('div', [
                            h('span', {},params.row.liveTimeD+"天"+params.row.liveTimeH+"小时")
                        ])
                    },
                },
                // {
                //     title: `${this.$t('禁用记录')}`,
                //     key: 'disableNum',
                //     minWidth: 130,
                //     align: "center",
                //     tooltip: true,
                //     resizable: true,
                //     render: (h, params) => {
                //         if (params.row.disableNum > 0) {
                //             return h('div', [
                //                 h('a', {
                //                     style: {},
                //                     on: {
                //                         click: () => {
                //                             this.getActualNum(params.row)
                //                         }
                //                     }
                //                 }, params.row.disableNum)
                //             ])
                //         } else {
                //             return h('div', [
                //                 h('a', {}, params.row.disableNum)
                //             ])
                //         }
                //     }
                // },
                {
                    title: `${this.$t('创建人')}`,
                    key: 'realname',
                    minWidth: 160,
                    align: "center",
                    tooltip: true,
                    resizable: true
                },
                {
                    title: `${this.$t('创建时间')}`,
                    key: 'createTime',
                    minWidth: 200,
                    align: "center",
                    tooltip: true,
                    resizable: true
                },
                {
                    title: `${this.$t('common.operation')}`,
                    slot: "action",
                    fixed: 'right',
                    minWidth: this.util.autoWidth(400, 370),
                    align: 'center'
                },
            ],
            delStatus:0,
            importExcelState: false,
            data: this.effPlanList,
            receivedataArr: [],
            position: []
        }
    },
    watch: {
        status() {
          this.searchList();
        },
        effPlanList(newVal) {
            this.data = newVal
        },
        effPlanTotal(newVal) {
            this.total = newVal
        },
        planIds(newVal) {
            this.delIds = newVal
        },
    },
    created() {
        this.getTableColumnsWidth(this.columns)
    },
    mounted() {
        this.getFaultCategory("设备类型")
    },
    methods: {
        getSearch(arg){
            this.searchParams=JSON.parse(JSON.stringify(arg[0]))
            this.pageNum=1;
            this.searchList()
        },
        importExcelChange(val) {
            this.importExcelState = false;
            if (val === "success") {
                this.$Message.success("导入成功");
                this.changeNum();
            }
        },
        //下载模板
        exportTemplate() {
            const filName = "有效计划导入模板";
            this.axios({
                method: "post",
                url: "/dms/devSpotCheckPlan/exportDevSpotCheckPlanTemplate",
                responseType: "blob",
            }).then((res) => {
                fileDownload(res, filName + ".xlsx");
            });
        },
        /*导入*/
        importExcelShow() {
            this.importExcelState = true;
        },
        deviceNameChange(val) {
            if (val) {
                this.searchParams.deviceType = val
            }
        },
        //获取故障数据
        getFaultCategory(name) {
            this.axios({
                method: 'get',
                url: '/dms/faultCategory/basicDict',
                params: { name }
            }).then(res => {
                if (res.code === 200) {

                    if (name === '故障分类') {
                        this.faultCategoryList = res.data.map(item => {
                            if (item.value) return item;
                        })
                    } else if (name === '设备类型') {
                        this.deviceTypeList = res.data.map(item => {
                            if (item.value) return item;
                        })
                    }
                } else {
                    this.$Message.warning(({ content: res.msg, duration: 6, closable: true }))
                }
            })
        },
        getDeviceNameList(deviceName) {
            this.axios({
                method: 'get',
                url: '/dms/dcmMaintainItem/selectDeviceNames',
                params: {
                    deviceName
                }
            }).then(res => {
                if (res.code == 200) {
                    this.deviceNameList = res.data.map(val => ({
                        label: val,
                        value: val
                    }))
                }
            })
        },
        onSelectChange(selection) {
            console.log(selection)
            let myArray = [];
            selection.map((item) => {
                myArray.push(item.id);
            });

            this.delIds = myArray;
        },
        deleteOk() {
            this.delLoading = true
            this.axios({
                method: 'POST',
                url: '/dms/devSpotCheckPlan/delByIds',
                data: this.delStatus==0?[this.delId]:this.delIds
            }).then(res => {

                if (res.code === 200) {
                    this.searchList()
                    this.$Message.success(({ content: '删除成功！', duration: 2, closable: true }));
                } else {
                    this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
                }
            }).finally(() => {
                this.delLoading = false
                this.delFaultCodeShowF = false
            })
        },
        confirm(row) {
            //点击展示提示删除弹窗
            // this.confirmFaultCodeShowF = true;
            // this.planId = row.id
            // this.disabledStatus = 0
            // console.log(row, 'row')
            this.axios({
                url:'/dms/devSpotCheckPlan/updateStatusById',
                method:'post',
                params:{
                    id:row.id,
                    status:row.status=='0'?'1':'0'
                },
            }).then(res=>{
                if (res.code==200) {
                    this.$Message.success(({ content: '操作成功！', duration: 2, closable: true }));
                }else this.$Message.warning(({ content: '操作失败！', duration: 2, closable: true }));
                this.searchList();
            })
        },
        deleteRow(row) {
            //点击展示提示删除弹窗
            this.delFaultCodeShowF = true;
            this.delId = row.id
            this.delStatus = 0
            console.log(row, 'row')
        },
        handleBatchDelete() {
            console.log('批量')
            //点击展示提示删除弹窗
            this.delFaultCodeShowF = true;
            this.delStatus = 1
        },
        handleBatchDisabled() {
            this.disabledStatus = 1
            this.confirmFaultCodeShowF = true
        },
        disabledCancel() {
            this.confirmFaultCodeShowF = false
            this.$refs.disabledPlanValidate.resetFields()
        },
        disabledOk() {
            if (this.disabledStatus == 0) {
                let data = {
                    planId: this.planId,
                    disableCycle: this.formInline.disableCycle,
                    reason: this.formInline.reason,
                }
                this.$refs.disabledPlanValidate.validate(valid => {
                    if (valid) {
                        this.disabledLoading = true
                        this.axios({
                            method: 'post',
                            url: '/dms/dcmMaintainDisableRecord/disable',
                            data
                        }).then(res => {

                            if (res.code === 200) {
                                this.searchList()
                                this.$Message.success(({ content: '禁用成功！', duration: 2, closable: true }));
                            } else {
                                this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
                            }
                        }).finally(() => {
                            this.confirmFaultCodeShowF = false
                            this.disabledLoading = false
                            this.$refs.disabledPlanValidate.resetFields()
                        })
                    }
                })
            } else {
                let data = {
                    planIds: this.delIds.toString(),
                    disableCycle: this.formInline.disableCycle,
                    reason: this.formInline.reason,
                }
                this.$refs.disabledPlanValidate.validate(valid => {
                    if (valid) {
                        this.disabledLoading = true
                        this.axios({
                            method: 'post',
                            url: '/dms/dcmMaintainDisableRecord/batchDisable',
                            data
                        }).then(res => {

                            if (res.code === 200) {
                                this.searchList()
                                this.$Message.success(({ content: '批量禁用成功！', duration: 2, closable: true }));
                            } else {
                                this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
                            }
                        }).finally(() => {
                            this.confirmFaultCodeShowF = false
                            this.disabledLoading = false
                            this.$refs.disabledPlanValidate.resetFields()
                        })
                    }
                })
            }
        },
        look(row) {
            this.$emit('changeDetailVisible', true, row.id)
        },
        getActualNum(row) {
            this.actualShowF = true
            this.getActualDetail(row.id)

        },
        getActualDetail(planId) {
            this.axios({
                method: 'get',
                url: '/dms/dcmMaintainDisableRecord/list',
                params: {
                    planId
                }
            }).then(res => {

                if (res.code === 200) {
                    this.receivedataArr = res.data
                } else {
                    this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
                }
            }).finally(() => {
            })
        },
        reset() {
            this.searchParams = {}
            this.$refs.CascaderInfo.value = []
            this.changeNum();
        },
        //分页
        changeNum() {
            this.pageNum = 1;
            this.searchList();
        },
        changePageSize(pageSize) {
            this.pageSize = pageSize;
            this.searchList();
        },
        changePageNum(val) {
            this.pageNum = val;
            this.searchList();
        },
        searchList() {
            let data = {
                status: this.status,
                pageNum: this.pageNum,
                pageSize: this.pageSize,
                ...this.searchParams
            };
            this.axios({
                method: 'post',
                url: '/dms/devSpotCheckPlan/getDevSpotCheckPlanList',
                data
            }).then(res => {

                if (res.code === 200) {
                    this.data = res.data.records
                    this.total = res.data.total
                } else {
                    this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
                }
            })
        },
        edit(row, str) {
            if (str === 'copy') {
                this.$store.commit('detail/SET_COPYSTATUS', true)
            } else {
                this.$store.commit('detail/SET_COPYSTATUS', false)
            }
            this.$emit('addMaintain', true, row)
        },
    },
}
</script>

<style scoped lang="scss">
</style>
